<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit" :disabled="isDisabled">
      <van-field
        v-model="telephone"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的格式'
          }
        ]"
      />
      <van-field
        v-model="authcode"
        name="code"
        label="验证码"
        placeholder="验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请输入正确的格式' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isDisabled"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入抽取方法
import { userLogin } from '../../api/login'
export default {
  name: 'login',
  data () {
    return {
      telephone: '13662613212',
      authcode: '246810',
      isLoading: false,
      isDisabled: false
    }
  },
  methods: {
    onSubmit (value) {
      // 开启loading
      this.isLoading = true
      this.isDisabled = true

      userLogin(value)
        .then(res => {
          console.log(res)
          // 轻提示
          this.$toast.success('登录成功')
          localStorage.setItem(res.data.data)
          setTimeout(() => {
            // 登录成功后关闭加载状态
            this.isLoading = false
            this.isDisabled = false
          }, 500)
        })
        .catch(res => {
          console.log(res)
          this.$toast.fail('登录失败')
          setTimeout(() => {
            // 登录失败后关闭加载状态
            this.isLoading = false
            this.isDisabled = false
          }, 500)
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .van-nav-bar {
    background-color: #3496f8;
    .van-nav-bar__title {
      color: #e6e7fb;
    }
  }
}
</style>
